package com.star.bookstore.product.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.star.bookstore.common.utils.PageUtils;
import com.star.bookstore.common.utils.Query;

import com.star.bookstore.product.dao.AttrDao;
import com.star.bookstore.product.entity.AttrEntity;
import com.star.bookstore.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrDao attrDao;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            wrapper.eq("attr_id",key).or().like("book_name",key).or().
                    like("author",key).or().like("addr_college_name",key);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        //获取查询好的page中的records数据，进行相应的修改
        List<AttrEntity> attrEntityList = page.getRecords().stream().map(attr -> {
            Date shelveDate = attr.getShelveDate();
            String shelveDateStr = new SimpleDateFormat("yyyy年 MM月 dd日").format(shelveDate);
            attr.setShelveDateStr(shelveDateStr);
            return attr;
        }).collect(Collectors.toList());

        //将page数据用pageUtils封装起来，并且使用setList更新其中records数据
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrEntityList);

        return pageUtils;
    }

    @Override
    public AttrEntity getByCategoryId(Long bookId) {
        return attrDao.selectByCategoryId(bookId);
    }

}